﻿Imports System.Text
Imports System.Xml.Serialization
Imports System.IO
Imports System.Security.Principal

Public Class Tools

#Region "Read/Write Settings"

    ''' <summary>
    ''' Diese Funktion serialisiert ein Objekt  und speichert es als XML-Format Datei im UTF-8 Zeichensatz
    ''' </summary>
    ''' <param name="Obj">Das zu serialisierende Objekt</param>
    ''' <param name="FileName">Die XML Datei in der das Ergebnis gespeichert werden soll</param>
    Public Sub XMLSerialize(ByVal Obj As Object, ByVal FileName As String)
        Dim XML As New XmlSerializer(Obj.GetType)
        Dim FS As New StreamWriter(FileName, False, System.Text.Encoding.UTF8)
        XML.Serialize(FS, Obj)
        FS.Close()
    End Sub

    ''' <summary>
    ''' Diese Funktion deserialisiert eine XML Datei mit dem UTF-8 Zeichensatz und gibt das Ergebnis in ein Objekt zurück
    ''' </summary>
    ''' <param name="FileName">Die XML Datei aus der gelesen werden soll</param>
    Public Function XMLDeSerialize(ByVal Obj As Object, ByVal FileName As String) As Object
        Dim XML As New XmlSerializer(Obj.GetType)
        Dim FS As New StreamReader(FileName, System.Text.Encoding.UTF8)
        Dim RetObj As Object = XML.Deserialize(FS)
        FS.Close()
        Return RetObj

    End Function


#End Region

#Region "Allgemeine Funktionen"

    Public Function isx64() As Boolean

        If IntPtr.Size = 8 Then
            Return True
        Else
            Return False
        End If

    End Function

    Public Function isAdministrator() As Boolean

        Dim pricipal As New WindowsPrincipal(WindowsIdentity.GetCurrent())
        Dim hasAdministrativeRight As Boolean = pricipal.IsInRole(WindowsBuiltInRole.Administrator)

        Return hasAdministrativeRight

    End Function

    Public Function IsLinux() As Boolean
        Dim p As Integer = CInt(Environment.OSVersion.Platform)
        Return (p = 4) OrElse (p = 6) OrElse (p = 128)
    End Function

    Public Function GenerateSFDLFileUID(ByVal _sfdl_file As SFDL.File.SFDLFile) As String

        Dim _raw_uuid As String = String.Empty
        Dim _hash_helper As New Core.Hashing

        _raw_uuid = _sfdl_file.Packages(0).Packagename

        _raw_uuid = _raw_uuid & _sfdl_file.ConnectionInfo.Host

        _raw_uuid = _raw_uuid & (_sfdl_file.ConnectionInfo.Port * _sfdl_file.MaxDownloadThreads).ToString

        If _sfdl_file.Packages(0).BulkFolderMode = False Then
            _raw_uuid = _raw_uuid & _sfdl_file.Packages(0).FileList(0).FileFullPath
        Else
            _raw_uuid = _raw_uuid & _sfdl_file.Packages(0).BulkFolderList(0).BulkFolderPath
        End If

        Return _hash_helper.MD5StringHash(_raw_uuid)

    End Function

    Public Function ConvertCharacterEncoding(ByVal _enum_encoding As SFDL.File.CharacterEncoding.CharacterEncoding) As System.Text.Encoding

        Select Case _enum_encoding

            Case SFDL.File.CharacterEncoding.CharacterEncoding.Standard

                Return System.Text.Encoding.Default

            Case SFDL.File.CharacterEncoding.CharacterEncoding.UTF8

                Return System.Text.Encoding.UTF8

            Case SFDL.File.CharacterEncoding.CharacterEncoding.UTF7

                Return System.Text.Encoding.UTF7

            Case SFDL.File.CharacterEncoding.CharacterEncoding.ASCII

                Return System.Text.Encoding.ASCII

            Case Else

                Return System.Text.Encoding.Default

        End Select

    End Function

    ''' <summary>
    ''' Konvertiert eine Dezimale Zeitangabe in eine lesbare Angabe.
    ''' </summary>
    Public Function ConvertDecimal2Time(ByVal value As Double) As String
        Try
            Dim valueTime As TimeSpan = TimeSpan.FromMinutes(value)
            If valueTime.Hours.Equals(0) Then
                Return String.Format("{0:D2}:{1:D2}", valueTime.Minutes, valueTime.Seconds)
            End If
            Return String.Format("{0:D2}:{1:D2}:{2:D2}", valueTime.Hours, valueTime.Minutes, valueTime.Seconds)
        Catch
            Return "0"
        End Try
    End Function

    ''' <summary>
    ''' Function to download Image from website
    ''' </summary>
    ''' <param name="_URL">URL address to download image</param>
    ''' <return>Image</return>
    Public Function DownloadImage(ByVal _URL As String) As System.Drawing.Image

        Dim _tmpImage As System.Drawing.Image = Nothing

        Try
            ' Open a connection
            Dim _HttpWebRequest As System.Net.HttpWebRequest = CType(System.Net.HttpWebRequest.Create(_URL), System.Net.HttpWebRequest)

            _HttpWebRequest.AllowWriteStreamBuffering = True

            ' You can also specify additional header values like the user agent or the referer: (Optional)
            _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"

            ' set timeout for 20 seconds (Optional)
            _HttpWebRequest.Timeout = 20000

            ' Request response:
            Dim _WebResponse As System.Net.WebResponse = _HttpWebRequest.GetResponse()

            ' Open data stream:
            Dim _WebStream As System.IO.Stream = _WebResponse.GetResponseStream()

            ' convert webstream to image
            _tmpImage = System.Drawing.Image.FromStream(_WebStream)

            ' Cleanup
            _WebResponse.Close()
        Catch _Exception As Exception
            ' Error
            Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
            Return Nothing
        End Try

        Return _tmpImage

    End Function

    Public Function SecToHMS(ByVal Sec As Double) As String
        '
        Dim ts As TimeSpan
        Dim totHrs As Integer
        Dim H, M, S, HMS As String
        '
        'Place milliseconds into timespand variable
        'to expose conversion properties
        ts = TimeSpan.FromSeconds(Sec)
        '
        'Get H M S values and format for leading zero
        'Add a trailing semi colon on Hours and minutes
        'Total hours will allow display of more than 24 hrs
        'while minutes and seconds will be limited to 0-59
        '
        totHrs = Math.Truncate(ts.TotalHours) 'strip away decimal points
        H = Format(totHrs, "0#") & ":"
        M = Format(ts.Minutes, "0#") & ":"
        S = Format(ts.Seconds, "0#")
        '
        'Combine Hours Minutes and seconds into HH:MM:SS string
        HMS = H & M & S
        '
        Return HMS

    End Function

    ''' <summary>
    ''' Öffnet den Windows Explorer mit dem angebenen Pfad
    ''' </summary>
    Public Sub OpenExplorer(ByVal path As String)
        Dim p As New ProcessStartInfo
        p.Arguments = "/e," & path & ""
        p.FileName = IO.Path.Combine(Environment.GetEnvironmentVariable("systemroot"), "explorer.exe")
        p.UseShellExecute = False
        Process.Start(p)
    End Sub


#End Region


End Class
